package pacman;

import pacman.objects.*;
import java.awt.Graphics;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * The characters class stores all Moveable objects of a level
 * @author Carlos Massera Filho
 */
public class Characters
{
  private Ghost[] ghosts = null;
  private PacMan pacman = null;

  /**
   * The loadCharacters function loads all character of a level from a file
   * @param filename The name of the file to be loaded
   * @throws FileNotFoundException
   * @throws IOException
   */
  public void loadCharacters(String filename) throws FileNotFoundException, IOException
  {
    FileReader reader = new FileReader(new File(filename));
    BufferedReader readerBuffer = new BufferedReader(reader);

    String mapLine = null;
    int startX,
        startY;

    mapLine = readerBuffer.readLine();
    int numberOfCharacters = (mapLine.charAt(0) - 48) * 100 + (mapLine.charAt(1) - 48) * 10 + mapLine.charAt(2) - 48;
    ghosts = new Ghost[numberOfCharacters - 1];

    for (int i = 0; i <= ghosts.length; i++)
    {
      mapLine = readerBuffer.readLine();
      switch(mapLine.charAt(0))
      {
        case 'P':
          startX = (mapLine.charAt(1) - 48) * 100 + (mapLine.charAt(2) - 48) * 10 + mapLine.charAt(3) - 48;
          startY = (mapLine.charAt(4) - 48) * 100 + (mapLine.charAt(5) - 48) * 10 + mapLine.charAt(6) - 48;
          this.pacman = new PacMan((float)startX,(float)startY);
        break;
        case 'G':
          startX = (mapLine.charAt(1) - 48) * 100 + (mapLine.charAt(2) - 48) * 10 + mapLine.charAt(3) - 48;
          startY = (mapLine.charAt(4) - 48) * 100 + (mapLine.charAt(5) - 48) * 10 + mapLine.charAt(6) - 48;
          if(pacman == null)
            this.ghosts[i] = new Ghost((float)startX,(float)startY);
          else
            this.ghosts[i - 1] = new Ghost((float)startX,(float)startY);
        break;
      }
    }
  }

  /**
   *
   * @param i index of the ghost vector
   * @return returns the ghost object in position i of the vector
   */
  public Ghost getGhost(int i)
  {
      if (i < ghosts.length)
        return ghosts[i];
      else
        return null;
  }

  /**
   *
   * @return returns the pacman object
   */
  public PacMan getPacman()
  {
     return pacman;
  }

  /**
   * Draw all ghosts and pacman on the screen
   * @param g Graphic class to draw to
   */
  public void renderCharacters(Graphics g)
  {
    for (int i = 0; i < ghosts.length; i++)
    {
      if (ghosts[i].isVisible())
        ghosts[i].render(g);
    }
    pacman.render(g);
  }
}
